import json
import requests
import threading
from urllib import parse
import time
import re
import random

# 设置API
APIUrl = 'https://hk4e-api.mihoyo.com/event/gacha_info/api/getGachaLog'
# 使用session保持TCP连接，避免重复进行握手，速度由0.3s提高到0.15s
session = requests.Session()


# 定义卡池类
class Section():
    def __init__(self, name, gacha_type):
        self.name = name
        self.gacha_type = gacha_type


def getParams(url):
    # 获取params
    query_dict = parse.parse_qs(parse.urlparse(url).query)
    # 增加API中需要的params
    query_dict['page'] = 1
    query_dict['size'] = 20
    query_dict['end_id'] = 0
    return query_dict


def getItem(params, Section):
    params['gacha_type'] = Section.gacha_type

    Section.star = []  # 出货的角色名称
    Section.count = 0  # 抽卡次数
    breakFlag = False
    while breakFlag == False:
        # time.sleep(0.115)   # 防止访问过于频繁被ban
        startRound = time.perf_counter()    # 一次请求开始计时
        while True:
            response = session.get(APIUrl, params=params)
            if json.loads(response.text)['data'] != None:   # 访问过于频繁返回空数据需要再次请求
                break
        # 以下处理数据
        result = json.loads(response.text)['data']['list']
        if result == []:    # 若尾页大小刚好为size则无法判断是否结束，会再次请求，但请求result无数据
            break
        if len(result) < 20:    # 说明是尾页，不需要再请求，可以减少一次请求
            breakFlag = True
        Section.count += len(result)    # 抽卡总数
        for item in result:
            if item['rank_type'] == '5':    # 五星
                Section.star.append(item['name'])
        # 更新params
        params['page'] += 1
        params['end_id'] = result[len(result)-1]['id']
        finishRound = time.perf_counter()   # 一次请求结束计时
        print(round(finishRound - startRound, 5))

    return result


def get(customUrl):
    start = time.perf_counter()

    # 正则匹配url
    pattern = re.compile(
        r'(https:\/\/webstatic.mihoyo.com(.*)#\/log)')
    customUrl = pattern.findall(customUrl)[0][0]

    # 从url获取params
    params = getParams(customUrl)

    SectionList = []
    SectionList.append(Section('角色活动池', 301))
    SectionList.append(Section('武器活动池', 302))
    # SectionList.append(Section('常驻祈愿', 200))
    SectionList.append(Section('新手祈愿', 100))

    # 由于API有end_id限制，每个池只能单线程
    # 这里建立线程池为每个池建立一个线程，异步获取
    threadList = []
    for i in range(len(SectionList)):
        threadList.append(threading.Thread(
            target=getItem, args=[params.copy(), SectionList[i]]))
        threadList[i].start()
    # 实现同步，父进程等待子线程完成
    for thread in threadList:
        thread.join()

    finish = time.perf_counter()  # 总时间结束计时
    print(round(finish - start, 2))

    # 以下处理返回文本
    randomTextList = ['在夜空所有星星熄灭的时候，所有梦想、所有溪流，都能汇入同一片大海中，那时我们终会相见。',
                      '只要不失去你的崇高，整个世界都会为你敞开。',
                      '不管当下的境遇如何，提瓦特大陆的星空永远会有你的位置。',
                      '只要你的渴望尚未平息，那抬头应该可以看到那无光的闪耀吧。',
                      '当你来到时间的尽头，便会与过去未来所有因缘之人重逢。',
                      '除了时间，什么也没留下，风带来故事的种子，时间使其发芽。',
                      '当你重新踏上旅途之后，一定要记得旅途本身的意义。提瓦特的飞鸟、诗和城邦，女皇、愚人和怪物……都是你旅途的一部分。终点并不意味着一切，在抵达终点之前，用你的眼睛，多多观察这个世界吧……']

    text = '旅行者：'
    for i in range(len(SectionList)):
        text += '\n\n你在 {name} 中抽卡 {count} 次\n'.format(
            name=SectionList[i].name, count=SectionList[i].count)
        if SectionList[i].count == 0:   # 判断没有出货的情况
            text += '还没有伙伴加入你的队伍，再多祈愿几次吧！'
        else:
            for charactor in SectionList[i].star:
                text += charactor + ' '
            text += '加入了你的队伍'
            text += '\n平均{}抽出货'.format(round(SectionList[i].count /
                                             len(SectionList[i].star)))
    text += '\n\n' + random.choice(randomTextList)
    print(text)
    return text


if __name__ == '__main__':
    get('页无法打开位于 https://webstatic.mihoyo.com/hk4e/event/e20190909gacha/index.html?authkey_ver=1&sign_type=2&auth_appid=webview_gacha&init_type=301&gacha_id=13d0c223ab4131d488fae6508cd2c564c871b2&timestamp=1637711098&lang=zh-cn&device_type=mobile&ext=%7b%22loc%22%3a%7b%22x%22%3a-4298.5537109375%2c%22y%22%3a215.4827117919922%2c%22z%22%3a-4242.97119140625%7d%2c%22platform%22%3a%22Android%22%7d&game_version=CNRELAndroid2.3.0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